package org.nacos.zuul_jwt.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;

/**
 * @author A夜兔A
 * @data 2022年04月18日 14:31
 */
public class JWTUtils {
    /**
     * 签名
     */
    private static final String SING="";

    /**
     * 生成token
     * @return
     */
    public static String getToken(String username,String pasword){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,30);


        String token = JWT.create()
                //用户名
                .withClaim("username", username)
                //密码(正式使用的时候不要存放密码）
                .withClaim("password", pasword)
                //指定令牌过期时间
                .withExpiresAt(instance.getTime())
                //添加签名
                .sign(Algorithm.HMAC256(SING));

        return token;
    }


    /**
     * 验证token
     */
    public static Result jwtVerify(String token){
        //验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SING)).build();
        //获得验证结果
        try{
            DecodedJWT verify = jwtVerifier.verify(token);
        }catch (SignatureVerificationException sve){
            return Result.error("签名不一致");
        }catch (AlgorithmMismatchException ame){
            return Result.error("算法不匹配");
        }catch (TokenExpiredException tee){
            return Result.error("令牌过期");
        }catch (InvalidClaimException ice){
            return Result.error("payload异常");
        }
        return Result.error("验证通过");

    }


    /**
     * 获取token信息的方法
     *
     */

    public static DecodedJWT getTokenMessage(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        verify.getClaim("username").asString();
        verify.getClaim("password").asString();
        return verify;
    }
}
